#include "COMMON.h"

#define BACKLOG 5
int main()
{
    EnableFile();
    // 创建 数据报socket
    int sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if(sfd == -1)
        LOG(FATAL, "socket create failed");
    
    // 移除文件
    if(remove(SV_SOCK_PATH) == -1 && errno != ENOENT)
        LOG(FATAL, "remove-%s", SV_SOCK_PATH);
    
    // 初始化地址格式
    struct sockaddr_un SVaddr;
    memset(&SVaddr, 0, sizeof(struct sockaddr_un));
    SVaddr.sun_family = AF_UNIX;
    strncpy(SVaddr.sun_path, SV_SOCK_PATH, sizeof(SVaddr.sun_path) - 1);

    // 绑定
    if(bind(sfd, (struct sockaddr*)&SVaddr, sizeof(struct sockaddr_un)) == -1)
        LOG(FATAL, "bind failed");
    
    // 接收消息，将消息转化为大写格式，并返回给客户端
    socklen_t len = 0;
    ssize_t numBytes = 0;
    struct sockaddr_un CLaddr;
    char buf[BUF_SIZE];
    for(; ;)
    {
        len = sizeof(struct sockaddr_un);
        numBytes = recvfrom(sfd, buf, BUF_SIZE, 0, (struct sockaddr*)&CLaddr, &len);
        if(numBytes == -1)
        {
            LOG(ERROR, "recvform failed");
        }
            
        printf("Server received %ld bytes from %s\n", (long)numBytes, CLaddr.sun_path);
        
        // 处理消息：转换为大写格式
        for(int j = 0; j < numBytes; j++)
        {
            buf[j] = toupper((unsigned char)buf[j]);
        }
        // 返回客户端
        if(sendto(sfd, buf, numBytes, 0, (struct sockaddr*)&CLaddr, len) != numBytes)
            LOG(FATAL, "sendto");
        
    }
    LOG(INFO, "server exit");
    return 0;
}